import {SelectQueryBuilder} from "typeorm";

export class PageQuery<T extends object> {
    pageNum: number;
    pageSize: number;
    param: T;

    static isPage(query: PageQuery<any>): boolean {
        if (!query.pageNum || !query.pageSize || query.pageNum == 0) {
            return false;
        }
        return true;
    }

    static skip(query: PageQuery<any>): number {
        query.pageNum = query.pageNum? query.pageNum : 1;
        query.pageSize = query.pageSize? query.pageSize : 1;
        return (query.pageNum - 1) * query.pageSize;
    }

    static async getRawManyAndCount(query: PageQuery<any>, queryBuilder: SelectQueryBuilder<any>) : Promise<[any[], number]> {
        let list = [];
        let count = 0;

        if (!this.isPage(query)) {
            list = await queryBuilder.getRawMany()
        } else {
            list = await queryBuilder.offset(this.skip(query)).limit(Number(query.pageSize)).getRawMany();
        }
        count = await queryBuilder.getCount();
        return [list, count];
    }

    static async getManyAndCount(query: PageQuery<any>, queryBuilder: SelectQueryBuilder<any>) : Promise<[any[], number]> {
        if (!this.isPage(query)) {
            return  await queryBuilder.getManyAndCount();
        } else {
            return await queryBuilder.offset(this.skip(query)).limit(Number(query.pageSize)).getManyAndCount();
        }
    }
}
